/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cfg.session;

import cn.easyplatform.studio.cfg.SessionManager;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.LoginUserVo;
import cn.easyplatform.type.StateType;

import java.util.Collection;
import java.util.Map;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class StdSessionManager implements SessionManager {

	private Map<String, LoginUserVo> sess;

	@SuppressWarnings("unchecked")
	StdSessionManager(CommandContext cc) {
		sess = (Map<String, LoginUserVo>) cc.getAppAttribute("ep_login_user");
	}

	@Override
	public void setUser(LoginUserVo user) {
		synchronized (sess) {
			sess.put(user.getUserId(), user);
		}
	}

	@Override
	public boolean removeUser(LoginUserVo user) {
		synchronized (sess) {
			LoginUserVo other = sess.get(user.getUserId());
			if (other != null && user == other) {
				sess.remove(user.getUserId());
				return true;
			}
			return false;
		}
	}

	@Override
	public Collection<LoginUserVo> getUsers() {
		return sess.values();
	}

	@Override
	public int checkUser(LoginUserVo user) {
		synchronized (sess) {
			LoginUserVo other = sess.get(user.getUserId());
			if (other == null)// 用户不存在
				return LoginUserVo.ONLINE_NONE;
			if (other == user)// 同一个用户
				return LoginUserVo.ONLINE_SELF;
			else
				// 不同用户
				return LoginUserVo.ONLINE_OTHER;
		}
	}

	@Override
	public void setState(String userId, int state) {
		synchronized (sess) {
			LoginUserVo user = sess.get(userId);
			if (user != null)
				user.setState(state);
		}
	}

	@Override
	public void validateSessions() {
		synchronized (sess) {
			for (LoginUserVo user : sess.values()) {
				if (!user.validate()) {
					sess.remove(user.getUserId());
					user.setState(StateType.STOP);
				}
			}
		}
	}

	@Override
	public LoginUserVo getUser(String id) {
		return sess.get(id);
	}

}
